import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import routesArr from "./routes";
import store from "@/store";

const routes: Array<RouteRecordRaw> = routesArr;

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

/* // 取缓存的token判断是否登录
const token = localStorage.getItem("token");
router.beforeEach((to, from, next) => {
  // 跳转的路由需要登录但未登录，就跳转登录页
  if (to.meta.requiredLogin && !token) {
    return next("/login");
  }
  if (to.meta.redirectAlreadyLogin && token) {
    return next("/");
  }
  next();
}); */

router.beforeEach((to, from, next) => {
  const { user, token } = store.state;
  const { requiredLogin, redirectAlreadyLogin } = to.meta;

  //登录判断
  if (!user.isLogin) {
    // 未登录
    if (token) {
      store
        .dispatch("fetchCurrentUser")
        .then((res) => {
          if (redirectAlreadyLogin) {
            // localStorage.setItem
            next("/");
          } else {
            next();
          }
        })
        .catch((err) => {
          console.log(err);
          // token 重新登陆
          store.commit("logOut");
        });
    } else {
      if (requiredLogin) {
        next("/login");
      }
      next();
    }
  } else {
    // if (requiredLogin && !token) {
    //   next("/login");
    // } else

    if (redirectAlreadyLogin) {
      //已登录
      next("/");
    } else {
      next();
    }
  }
});

export default router;
